package com.wang.transfer.util.algorithm;

import java.util.Arrays;

/**
 * 寻找两个正序数组的中位数
 */
public class FindMedianSortedArrays {

    public static void main(String[] args) {
        int[] num1 = {1, 5};
        int[] num2 = {2, 4};
        double v = new FindMedianSortedArrays().sortedArrays(num1, num2);
        System.out.println(v);
    }

    public double sortedArrays(int[] nums1, int[] nums2) {
        int l1 = nums1.length;
        int l2 = nums2.length;
        int[] num = new int[l1 + l2];
        int max = Math.max(l1, l2);
        int min = Math.min(l1, l2);
        int[] maxArray = l1 > l2 ? nums1 : nums2;
        for (int i = 0; i < max; i++) {
            if (i < min) {
                num[2 * i] = nums1[i];
                num[2 * i + 1] = nums2[i];
            } else {
                num[i + min] = maxArray[i];
            }
        }
        Arrays.sort(num);
        if (num.length == 0) {
            return 0;
        }
        int n = (l1 + l2) / 2;
        double z;
        if ((l1 + l2) % 2 != 0) {
            z = num[n];
        } else {
            z = (double) (num[n - 1] + num[n]) / 2;
        }
        return z;
    }
}
